package com.hsav.kcxb.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.hsav.kcxb.R;
import com.hsav.kcxb.activity.PlayActivity;
import com.hsav.kcxb.adapter.UserRvAdapter;
import com.hsav.kcxb.bean.SingItemBean;
import com.hsav.kcxb.main.MSYS;
import com.kcbsdk.AFetchType;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyRankBa.ARankTopList;
import com.kcbsdk.MyTools.ACloudType;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import main.MAPI;

import static com.hsav.kcxb.main.MSYS.MSTRING;
import static com.hsav.kcxb.main.MSYS.mMyManage;
import static com.hsav.kcxb.main.MSYS.mMyRankBa;
import static com.hsav.kcxb.main.MSYS.mMyTools;


/**
 * Created by zhao on 16-12-8.
 */

public class SongListFragment extends Fragment {

    private static final int MSG_REFRESH_DATA = 0x001;
    private static final int MSG_PAGE_DATA = 0X002;
    private View mRootView;
    private ImageView mTopImg;
    private RecyclerView mSingRv;
    private ArrayList<SingItemBean> mItemList = new ArrayList<SingItemBean>();
    private UserRvAdapter mAdapter;
    private GridLayoutManager layoutManager;
    public static final String TAG = SongListFragment.class.getSimpleName();
    private int[] mImageIds = new int[]{
            R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five,
            R.drawable.six, R.drawable.seven, R.drawable.eight, R.drawable.nighteen, R.drawable.ten
    };
    private List<ARankTopList> mUserInfoList;
    private int mTopAreaData;

    private ImageView mPlayIconIv;
    private PtrFrameLayout mPtrFrame;
    private TextView mAreaTv;
    private ImageView mAreaIv;
    private LayoutInflater mInflater;
    private PopupWindow mPopWindow;
    private Activity mActivity;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    public void OnShowWindow(Activity activity, boolean show){
        if (show && mMyRankBa != null){
            mMyRankBa.setUiEventCallBack(activity, new EventHandler() {
                @Override
                public void onComplete(int methodType, boolean isFail, String message){
                    if (methodType > 0){
                        if (isFail){
                            mMyRankBa.Toast(String.format("%s%s(%08x)", getString(R.string.methodError), message, methodType));
                        }
                        else {
                            if (mMyRankBa.isSucessTopListDbs(methodType)){
                               // mMyRankBa.Log("isEventTopListDbs 榜事件");
                                if (null != mMyRankBa.mARankTopList) {
                                    String gsLocal_1 = "";
                                    ARankTopList aRankTopList;
                                    int headCounter = 0;
                                    List<ARankTopList> userInfoList = new ArrayList<ARankTopList>();
                                    for (int counter = 0; counter < mMyRankBa.mARankTopList.length; counter++) {
                                        aRankTopList = mMyRankBa.mARankTopList[counter];
                                        userInfoList.add(aRankTopList);
                                        //mMyRankBa.Log("HeadFile "+aRankTopList.HeadFile);
                                        if (MAPI.GET_FILE_LENGTH(aRankTopList.HeadFile) > 100) {

                                            ++headCounter;
                                        }
                                    }
                                    mHandler.obtainMessage(MSG_REFRESH_DATA,userInfoList).sendToTarget();
                                    gsLocal_1 += String.format("\n有头像的%d个,榜数量%d个，共%d个", headCounter, mMyRankBa.mARankTopList.length, mMyRankBa.g4RankTopListMax);
//                            mMyTools.Toast(gsLocal_1);
//                                    MSTRING(gsLocal_1);
                                }
                                else {
                                    mMyRankBa.Toast("没有找到榜");
                                }
                            }

                        }
                    } else{
                        mMyTools.Log(String.format("isEventDownImgSmall %08x", mMyRankBa.mSvrRankBa.g4EventMethod));
                        if (mMyRankBa.isEventDownImgRank()){
                            mMyTools.Toast("有新的图片A");
                        }
                        if (mMyRankBa.isEventDownImgSmall()){
                            mMyTools.Toast("有新的图片B");
                        }
                    }
                }
            });
            mMyRankBa.selectCloudType(ACloudType.TYPE_KBA);
            mTopAreaData = mMyTools.getAreaRankData("全国", "", "");   //   北京市 "全国" "广东省", "深圳市", "宝安区"   "湖南省", "长沙市", "芙蓉区"
            mMyRankBa.fetchRankTopDbs(AFetchType.LIST_FRESHEN, mTopAreaData);
            MSTRING(String.format("SongListFragment mTopAreaData %04x", mTopAreaData));
        }
    }
    private void initKcbData(){          // 数据接口回调函数







//        mMyTools.Log(String.format("areaData %04x", mTopAreaData));

     //   mMyRankBa.fetchUserInfo(172998150, AHeadPortrait.IMG_LARGE);

//        // 数据接口
//        String gsLocal_1 = "全国的省列表：";
//        int gAreaProvinceQty[] = new int[1];
//        String mAreaProvince[] = mMyTools.getAreaProvinceList(gAreaProvinceQty);
//        for (int counter = 0; counter < gAreaProvinceQty[0]; counter++){
//            gsLocal_1 += String.format("%s ", mAreaProvince[counter]);
//        }
//        gsLocal_1 += "\n湖南省的市列表：";
//        int gAreaCityQty[] = new int[1];
//        String mAreaCity[] = mMyTools.getAreaCityList("湖南省", gAreaCityQty);
//        for (int counter = 0; counter < gAreaCityQty[0]; counter++){
//            gsLocal_1 += String.format("%s ", mAreaCity[counter]);
//        }
//
//        gsLocal_1 += "\n长沙市的区列表：";
//        int gAreaRegionsQty[] = new int[1];
//        String mAreaRegions[] = mMyTools.getAreaRegions("湖南省", "长沙市", gAreaRegionsQty);
//        for (int counter = 0; counter < gAreaRegionsQty[0]; counter++){
//            gsLocal_1 += String.format("%s ", mAreaRegions[counter]);
//        }
//        mMyTools.Toast(gsLocal_1);

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REFRESH_DATA:
                    if (msg.obj != null) {
                        mUserInfoList = (List<ARankTopList>) msg.obj;
                        if (mUserInfoList != null && mUserInfoList.size() > 0) {
                            mAdapter = new UserRvAdapter(getContext(), mUserInfoList);
                            mSingRv.setAdapter(mAdapter);
                            mPtrFrame.refreshComplete();
                            mAdapter.setOnClickListener(new UserRvAdapter.OnClickListener() {
                                @Override
                                public void onHandleClick(ARankTopList item) {
                                    MSTRING("SongListFragment onHandleClick" + item.NickName);
                                    Intent intent = MSYS.startPlayActivity(item.UserID, item.SongID, item.IsVideo, getContext());
                                    startActivity(intent);
                                }
                            });
                        }
                    }
                    break;
                case MSG_PAGE_DATA:
                    if (msg.obj != null) {
                        List<ARankTopList> userInfoList = (List<ARankTopList>) msg.obj;
                        mAdapter.addData(userInfoList);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.mInflater = inflater;
        mRootView = inflater.inflate(R.layout.frag_song_list_layout, container, false);
        mSingRv = (RecyclerView) mRootView.findViewById(R.id.rv_user_img);
        mPlayIconIv = (ImageView) mRootView.findViewById(R.id.iv_singlist_play);
        mPlayIconIv.setImageResource(R.drawable.play_animlist);
        mPtrFrame = (PtrFrameLayout) mRootView.findViewById(R.id.test_list_view_frame);
        mAreaTv = (TextView) mRootView.findViewById(R.id.tv_item_center);
        mAreaIv = (ImageView) mRootView.findViewById(R.id.iv_area);

        View viewPop = mInflater.inflate(R.layout.view_area, null);
        mPopWindow = new PopupWindow(viewPop, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        initPopView();

        setEventListener();
        AnimationDrawable animationDrawable = (AnimationDrawable) mPlayIconIv.getDrawable();
//        AnimationDrawable animationDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.play_animlist);
        animationDrawable.start();
        setImages();
        initRv();
        initRefreshView();
        mActivity = this.getActivity();
        initKcbData();
        return mRootView;
    }
    private void initPopView() {
        View viewPop = mInflater.inflate(R.layout.view_area, null);
        mPopWindow = new PopupWindow(viewPop, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        ListView provinceLv = (ListView)viewPop.findViewById(R.id.lv_area_province);
        ListView cityLv = (ListView)viewPop.findViewById(R.id.lv_area_province);
    }

    private void setEventListener() {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int xOff = getResources().getDimensionPixelOffset(R.dimen.pop_window);
                Log.i(TAG, "x = " + xOff);
                mPopWindow.showAsDropDown(v, -xOff / 2, 0);
            }
        };
        mAreaIv.setOnClickListener(clickListener);
        mAreaTv.setOnClickListener(clickListener);
    }

    private void initRefreshView() {
        //下拉刷新一些设置 详情参考文档
        mPtrFrame.setResistance(1.7f);
        mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        mPtrFrame.setDurationToClose(200);
        mPtrFrame.setDurationToCloseHeader(1000);
        // default is false
        mPtrFrame.setPullToRefresh(false);
        // default is true
        mPtrFrame.setKeepHeaderWhenRefresh(true);

        mPtrFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPtrFrame.autoRefresh();
            }
        }, 100);

        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                Log.i("refresh", "check");
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
//                mMyTools.Log("refresh begin");
                mMyRankBa.fetchRankTopDbs(AFetchType.LIST_FRESHEN, mTopAreaData);  // 重新读取榜
            }
        });
    }

    private void initRv() {
        layoutManager = new GridLayoutManager(getContext(), 6);
        mSingRv.setLayoutManager(layoutManager);
        mSingRv.addItemDecoration(new UserRvAdapter.SpaceDecoration(3));
        mAdapter = new UserRvAdapter(getContext(), 20);
        mSingRv.setAdapter(mAdapter);

//        mSingRv.addOnScrollListener(new LoadMoreListener(layoutManager) {
//            @Override
//            public void onLoadMore(int mCurrentPage) {
//                Log.i(TAG, "load more" + mCurrentPage);
//                getMoreContent();
//            }
//        });
        mSingRv.addOnScrollListener(mAdapter.new LoadMoreListener(mSingRv) {
            @Override
            public void onLoadMore(int mCurrentPage) {
                getMoreContent();
            }
        });
    }


    private void getMoreContent() {
        mMyTools.Log("getMoreContent");
        mMyRankBa.fetchRankTopDbs(AFetchType.LIST_MORE, mTopAreaData);
    }

    private void setImages() {
        for (int i = 0; i < mImageIds.length; i++) {
            SingItemBean item = new SingItemBean();
            item.setImgId(mImageIds[i]);
            mItemList.add(item);
        }
    }
}
